from django.http import JsonResponse
from django.views import View
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status, exceptions
from django.utils import timezone
from rest_framework_jwt.settings import api_settings
from user.models import SysUser, SysUserSerializer, SysUserFullSerializer


# Create your views here.
def index(request):
    return JsonResponse({'code': 200, 'message': 'Hello World!'})


class LoginView(APIView):
    def post(self, request):
        try:
            username = request.data.get('username')
            password = request.data.get('password')
            print(username)
            print(password)
            user = SysUser.objects.get(username=username, password=password)

            # 更新最后登录时间
            user.login_time = timezone.now()
            user.save()

            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            user_serializer = SysUserFullSerializer(user)
            user_data = user_serializer.data

        except SysUser.DoesNotExist:
            return JsonResponse({'code': 404, 'message': '用户名或者密码错误', 'ok': 'false'},
                                status=status.HTTP_404_NOT_FOUND)
        except exceptions.AuthenticationFailed as e:
            return JsonResponse({'code': 401, 'message': str(e), 'ok': 'false'},
                                status=status.HTTP_401_UNAUTHORIZED)
        except Exception as e:
            print(f'错误:{e}')
            return JsonResponse({'code': 500, 'message': '服务器错误', 'ok': 'false'},
                                status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        return JsonResponse({
            'code': 200,
            'message': '成功',
            'data': {
                'token': token,
                'user': user_data
            },
            'ok': 'true'
        }, status=status.HTTP_200_OK)


class LogoutView(APIView):
    def post(self, request):
        # 这里可以添加一些清理操作，比如删除用户的会话数据
        # 但通常情况下，前端会删除存储的Token
        return Response({
            'code': 200,
            'data': '',
            'message': '成功退出登录',
            'ok': 'true'
        }, status=status.HTTP_200_OK)


class AdminUserListView(APIView):

    def get(self, request):
        users = SysUser.objects.all()
        serializer = SysUserSerializer(users, many=True)
        return Response({
            'code': 200,
            'message': '成功',
            'data': serializer.data,
            'ok': 'true'
        }, status=status.HTTP_200_OK)


class AdminUserEditView(APIView):
    def put(self, request, user_id):
        try:
            user = SysUser.objects.get(id=user_id)
        except SysUser.DoesNotExist:
            return Response({
                'code': 404,
                'message': '用户不存在',
                'ok': 'false'
            }, status=status.HTTP_404_NOT_FOUND)

        serializer = SysUserSerializer(user, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response({
                'code': 200,
                'message': '成功',
                'data': serializer.data,
                'ok': 'true'
            }, status=status.HTTP_200_OK)
        return Response({
            'code': 400,
            'message': '数据无效',
            'ok': 'false',
            'errors': serializer.errors
        }, status=status.HTTP_400_BAD_REQUEST)


class BlogUserInfoView(APIView):
    def get(self, request):
        users = SysUser.objects.all()
        user_data = [{'id': user.id, 'nickname': user.nickname, 'avatar': user.avatar} for user in users]
        return Response({
            'code': 200,
            'message': '成功',
            'data': user_data,
            'ok': 'true'
        }, status=status.HTTP_200_OK)


class UserDetailView(APIView):
    def get(self, request):
        try:
            # 获取唯一的用户数据
            user = SysUser.objects.first()  # 获取第一个用户（唯一用户）
            if not user:
                return Response({
                    'code': 404,
                    'message': '用户不存在',
                    'ok': 'false'
                }, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'服务器错误: {str(e)}',
                'ok': 'false'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        # 使用新的序列化器返回所有字段
        serializer = SysUserFullSerializer(user)
        return Response({
            'code': 200,
            'message': '成功',
            'data': serializer.data,
            'ok': 'true'
        }, status=status.HTTP_200_OK)


class UserEditView(APIView):
    def put(self, request):
        try:
            # 获取唯一的用户数据
            user = SysUser.objects.first()  # 获取第一个用户（唯一用户）
            if not user:
                return Response({
                    'code': 404,
                    'message': '用户不存在',
                    'ok': 'false'
                }, status=status.HTTP_404_NOT_FOUND)

            # 检查是否修改了密码
            new_password = request.data.get('password')
            if new_password and new_password != user.password:
                # 如果密码被修改，退出登录
                logout_message = '密码已修改，请重新登录'
            else:
                logout_message = None

            # 使用新的序列化器更新用户信息
            serializer = SysUserFullSerializer(user, data=request.data, partial=True)
            if serializer.is_valid():
                serializer.save()
                response_data = {
                    'code': 200,
                    'message': '成功',
                    'data': serializer.data,
                    'ok': 'true'
                }
                if logout_message:
                    response_data['message'] = logout_message
                return Response(response_data, status=status.HTTP_200_OK)
            return Response({
                'code': 400,
                'message': '数据无效',
                'ok': 'false',
                'errors': serializer.errors
            }, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'服务器错误: {str(e)}',
                'ok': 'false'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
